import sublime, sublime_plugin
import re
import os
import traceback
DEBUG = True

lua_field_pat = ".+(?:(?P<self>self.)){1}" + \
                 "(?:(?P<varname>[a-zA-Z0-9_$]+))" + \
                 "(?:\s*=.+){1};?"
lua_field_pat = re.compile(lua_field_pat)

def matchdict(text):
    m = lua_field_pat.match(text)
    if m:
        return m.groupdict()
    else:
        return {}
def getSelections(view):
    position = 0
    selected = []
    sels     = view.sel()

    for sel in sels:
        lineRegions = view.lines(sel)
        for lineRegion in lineRegions:
            position = max(position, lineRegion.end())
            selected.extend(view.substr(lineRegion).split("\n"))

    selection_matches = []
    for line in selected:
        md = matchdict(line)
        if DEBUG:
            print(md,line)
        if md.get("self", None) is not None: # Make sure it's private or protected
            selection_matches.append(md)
    return {"position": position, "selections": selection_matches}
def name_convert_to_camel(name: str) -> str:
    """下划线转驼峰(小驼峰)"""
    str = re.sub(r'(_[a-z])', lambda x: x.group(1)[1].upper(), name)
    return str[0].upper() + str[1:]

class LuaSetterGetter(sublime_plugin.TextCommand):
    def run(self, edit):
        selections = getSelections(self.view)
        
        file_name = self.view.file_name()
        base_name = os.path.basename(file_name).replace(".lua","")
        if DEBUG:
            # print(file_name)
            # print(base_name)
            print("LuaSetterGetter11111111111111")
        region = self.view.find("return " + base_name,0)
        selection_matches = selections["selections"]
        properties = []
        insert_position = selections["position"]
        # print(region,"---------")
        if region.begin() !=-1:
            insert_position = region.begin()
        getter_arr = []
        setter_arr = []

        getterTemplate = """
function {0}:get{1}()
    return self.{2}
end
        """

        setterTemplate = """
function {0}:set{1}(v)
    self.{2} = v
end
        """
        print(len(selection_matches))
        if(len(selection_matches) == 0):
            sublime.message_dialog("选择的代码不是成员变量，无法创建get set函数")
            return
        for prop in selection_matches:
            property_name = prop['varname']
            setFunc = "set" + name_convert_to_camel(prop['varname'])
            getFunc = "get" + name_convert_to_camel(prop['varname'])
            print(setFunc,'1111')
            print(getFunc)
            if self.view.find(getFunc,0).begin() == -1:
                getter_arr.append(getterTemplate.format(base_name, name_convert_to_camel(prop['varname']), prop['varname']))
            else:
                sublime.message_dialog(getFunc + "函数已经存在,无需重复创建")
            if self.view.find(setFunc,0).begin() == -1:
                getter_arr.append(setterTemplate.format(base_name, name_convert_to_camel(prop['varname']), prop['varname']))
            else:
                sublime.message_dialog(setFunc + "函数已经存在,无需重复创建")

        # don't print anything if we don't have any instance members
        if len(getter_arr)==0 and len(setter_arr)==0:
            return
        try:
            # edit = self.view.begin_edit('lua_setter_getter',insert_position)
            properties_text = "\n" + "\n".join(getter_arr) + "\n" + "\n".join(setter_arr)
            insert_count = self.view.insert(edit, insert_position, properties_text)
            self.view.sel().clear()
            self.view.sel().add(sublime.Region(insert_position, (insert_position + insert_count)))
        except Exception as ex:
            if DEBUG:
                print(ex)
        finally:
            self.view.end_edit(edit)
